const Captcha = require("@/utils/captcha");
const Bcrypt = require("bcryptjs");
const Jwt = require("jsonwebtoken");
const Crypto = require("crypto");
const NodeCache = require("@/utils/node_cache");
const { getUserById, addUser } = require("@/models/admin/user-model");
const { getDeptById } = require("@/models/admin/dept-model");
const { getRoleById, getRoleMenus } = require("@/models/admin/role-model");
const { arrayToTree } = require("@/utils");
/**
 * 获取登录用户信息
 */
exports.user = async (req, res, next) => {
  try {
    const { username, id } = req.auth;
    var user = await getUserById({ id, username });
    if (!user) {
      throw new Error("账号不存在");
    }
    delete user.password;

    var department = await getDeptById({ id: user.dept_id });
    var role = await getRoleById({ id: user.role_id });
    res.backSuccess({ ...user, department, role });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取登录用户权限菜单
 */
exports.menus = async (req, res, next) => {
  try {
    const { id } = req.auth;
    var user = await getUserById({ id });
    if (!user) {
      throw new Error("账号不存在");
    }
    const result = await getRoleMenus(user.role_id);
    res.backSuccess(arrayToTree(result));
  } catch (error) {
    next(error);
  }
};

/**
 * 验证码
 */
exports.captcha = async (req, res, next) => {
  try {
    // 生成验证码
    const { data, text } = Captcha({ is_sum: true });
    // 生成唯一键
    const key = Crypto.randomUUID();
    // 存入redis
    NodeCache.set(key, text, 120);

    console.log(key, text);

    res.backSuccess({ image: data, key });
  } catch (error) {
    next(error);
  }
};

/**
 * 注册
 */
exports.register = async (req, res, next) => {
  try {
    const current_date = new Date();
    var bodyParams = req.body;
    var result;

    if (bodyParams.password !== bodyParams.confirm_password) {
      throw new Error("两次密码输入不一致");
    }
    // 校验账号是否存在
    result = await getUserById({ username: bodyParams.username });
    if (result) {
      throw new Error("账号已存在");
    }
    // 加密密码
    var bcryptPassword = Bcrypt.hashSync(bodyParams.password, 10);

    // 插入数据库
    result = await addUser({
      username: bodyParams.username,
      password: bcryptPassword,
      avatar: bodyParams.avatar,
      email: bodyParams.email,
      nickname: bodyParams.nickname,
      created_time: current_date,
      updated_time: current_date,
    });
    return res.backSuccess(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 登录
 */
exports.login = async (req, res, next) => {
  try {
    var queryParams = req.query;
    var validCode = NodeCache.get(queryParams.key);

    if (
      !validCode ||
      validCode.toLowerCase() != queryParams.code.toLowerCase()
    ) {
      throw new Error("验证码错误||已过期");
    }

    var result = await getUserById({ username: queryParams.username });

    if (!result || !Bcrypt.compareSync(queryParams.password, result.password)) {
      throw new Error("账号名||密码错误");
    }
    if (result.status !== 1) throw new Error("当前账号已冻结");
    var token = Jwt.sign(
      { id: result.id, username: result.username },
      process.env.JWT_KEY,
      { expiresIn: "24h" }
    );
    return res.backSuccess({
      id: result.id,
      username: result.username,
      token: token,
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 上传文件
 */
exports.upload = async (req, res, next) => {
  try {
    const current_date = new Date();
    const obj = {
      name: req.file.filename,
      path: "/uploads/" + req.file.filename,
      size: req.file.size,
      created_time: current_date,
      updated_time: current_date,
    };
    await DB.insert(TB.FILES, obj).execute();
    res.backSuccess({ ...obj, updated_time: "", created_time: "" });
  } catch (error) {
    next(error);
  }
};
